/**
 * @author: Loy-winters1224@163.com
 * @date: 2014-8-15-下午1:29:43
 */
package net.loyintean.pearlshell.wechat.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import net.loyintean.pearlshell.wechat.distribute.IMessageDistributor;
import net.loyintean.pearlshell.wechat.distribute.impl.DefaultMessageDistributorImpl;
import net.loyintean.pearlshell.wechat.messagepasser.IMessageParser;
import net.loyintean.pearlshell.wechat.messagepasser.impl.MessageParserImpl;
import net.loyintean.pearlshell.wechat.model.BaseMessageModel;
import net.loyintean.pearlshell.wechat.model.WeChatIdentityModel;
import net.loyintean.pearlshell.wechat.service.IMessageProcesser;

/**
 * joint to weixin.qq.com
 * 
 * @author Loy-winters1224@163.com
 * @version 2014-8-15.1.0.0
 */
public class JointServlet extends HttpServlet {

	private static final String CharacterEncoding = "UTF-8";

	private Logger logger = Logger.getRootLogger();

	private IMessageParser parser = new MessageParserImpl();

	private IMessageDistributor distributor = new DefaultMessageDistributorImpl();

	/**
	 *
	 */
	private static final long serialVersionUID = 2841779885599120095L;

	/**
	 * joint to weixin.qq.com, and valid developer identity with signature,
	 * timestamp, nonce and echostr.
	 * 
	 * @author Loy-winters1224@163.com
	 * @see javax.servlet.http.HttpServlet
	 *      #doGet(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 * 
	 */
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		WeChatIdentityModel identity = new WeChatIdentityModel(request);

		logger.info("doGet identity=" + identity);

		PrintWriter out = response.getWriter();

		if (identity.checkSignature()) {
			out.print(identity.getEchostr());
		} else {
			out.print("");
		}

		out.close();
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding(CharacterEncoding);
		BaseMessageModel message = parser.parse(request);

		IMessageProcesser processer = distributor.distribute(message);

		BaseMessageModel responseMessage = processer.process(message);

		String responseXml = responseMessage.asXml();
		responseMessage = null;

		logger.info("doPost for message=" + message + ", responseXml="
				+ responseXml);
		message = null;

		response.setCharacterEncoding(CharacterEncoding);
		PrintWriter out = response.getWriter();
		out.print(responseXml);
		out.close();
	}

}
